package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.KafkaMessageConstant;
import com.heima.model.search.entity.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class SyncArticleListener {

    @Resource
    private RestHighLevelClient restHighLevelClient;


    @KafkaListener(topics = KafkaMessageConstant.AP_ARTICLE_ES_SYNC_TOPIC,groupId = "article_es_sync")
    public void syncArticle(ConsumerRecord<String,String> record){

        String value = record.value();
        if (StringUtils.isNotBlank(value)) {
            SearchArticleVo articleVo = JSON.parseObject(value, SearchArticleVo.class);
            //1.创建请求对象
            IndexRequest request=new IndexRequest("app_article_info");
            //2.准备DSL语句
            request.id(articleVo.getId()+"");
            request.source(value, XContentType.JSON);
            //3.发送请求
            try {
                restHighLevelClient.index(request, RequestOptions.DEFAULT);
                log.info("导入数据到索引库成功，数据:{}",value);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("导入数据到索引库失败，失败原因:{},数据:{}",e.getMessage(),value);
            }
        }
    }
}
